package com.nbsaas.boot.shopping.ext.resource;

import com.nbsaas.boot.customer.api.apis.CustomerAddressApi;
import com.nbsaas.boot.customer.api.domain.response.CustomerAddressResponse;
import com.nbsaas.boot.order.api.apis.OrderAddressApi;
import com.nbsaas.boot.order.api.apis.OrderApi;
import com.nbsaas.boot.order.api.apis.OrderItemApi;
import com.nbsaas.boot.order.api.domain.request.OrderAddressRequest;
import com.nbsaas.boot.order.api.domain.request.OrderItemRequest;
import com.nbsaas.boot.order.api.domain.request.OrderRequest;
import com.nbsaas.boot.order.api.domain.response.OrderResponse;
import com.nbsaas.boot.pay.ext.apis.PaymentExtApi;
import com.nbsaas.boot.pay.ext.domain.request.OrderPayRequest;
import com.nbsaas.boot.product.api.apis.ProductApi;
import com.nbsaas.boot.product.api.apis.ProductSkuApi;
import com.nbsaas.boot.product.api.domain.response.ProductResponse;
import com.nbsaas.boot.product.api.domain.response.ProductSkuResponse;
import com.nbsaas.boot.rest.filter.Filter;
import com.nbsaas.boot.rest.request.RequestId;
import com.nbsaas.boot.rest.response.MapResponse;
import com.nbsaas.boot.rest.response.ResponseObject;
import com.nbsaas.boot.shopping.api.apis.ShoppingCartApi;
import com.nbsaas.boot.shopping.api.domain.field.ShoppingCartField;
import com.nbsaas.boot.shopping.api.domain.request.ShoppingCartRequest;
import com.nbsaas.boot.shopping.api.domain.simple.ShoppingCartSimple;
import com.nbsaas.boot.shopping.ext.apis.ShoppingCartSubmitApi;
import com.nbsaas.boot.shopping.ext.domain.request.ShoppingCartCheckoutRequest;
import com.nbsaas.boot.shopping.ext.domain.request.ShoppingCartSubmitRequest;
import com.nbsaas.boot.shopping.utils.OrderUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ShoppingCartSubmitResource implements ShoppingCartSubmitApi {

    @Resource
    private ShoppingCartApi shoppingCartApi;

    @Resource
    private CustomerAddressApi customerAddressApi;

    @Resource
    private ProductApi productApi;

    @Resource
    private ProductSkuApi productSkuApi;

    @Resource
    private OrderApi orderApi;

    @Resource
    private OrderAddressApi orderAddressApi;

    @Resource
    private OrderItemApi orderItemApi;

    @Resource
    private PaymentExtApi paymentExtApi;


    @Transactional
    @Override
    public ResponseObject<?> submit(ShoppingCartSubmitRequest request) {
        ResponseObject<MapResponse> result = new ResponseObject<>();
        result.setData(new MapResponse());
        List<ShoppingCartSimple> carts = shoppingCartApi.listData(
                Filter.eq(ShoppingCartField.creator, request.getCreator()),
                Filter.eq(ShoppingCartField.checked, true)
        );
        if (carts == null||carts.isEmpty()) {
            result.setCode(500);
            result.setMsg("请选择商品");
            return result;
        }
        if (request.getAddress()==null){
            result.setCode(501);
            result.setMsg("请选择收货地址");
            return result;
        }
        CustomerAddressResponse address = customerAddressApi.oneData(Filter.eq("id", request.getAddress()));
        if (address == null){
            result.setCode(502);
            result.setMsg("请选择收货地址");
            return result;
        }
        List<ShoppingCartSimple> skuList=new ArrayList<>();
        //检查库存
        //同步价格
        for (ShoppingCartSimple cart : carts) {
            ProductResponse product = productApi.oneData(Filter.eq("id", cart.getProduct()));
            if (product.getSkuEnable()) {
                ProductSkuResponse sku = productSkuApi.oneData(Filter.eq("id", cart.getSku()));
                if (sku == null) {
                    continue;
                }
                cart.setPrice(sku.getPrice());
            } else {
                cart.setPrice(product.getPrice());
            }
            skuList.add(cart);
        }


        int sum = carts.stream().mapToInt(ShoppingCartSimple::getNum).sum();
        BigDecimal total = carts.stream()
                .map(item -> item.getPrice().multiply(new BigDecimal(item.getNum())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        OrderRequest orderRequest=new OrderRequest();
        orderRequest.setCustomerId(request.getCreator());
        orderRequest.setAmount(total);
        orderRequest.setNum(sum);
        orderRequest.setState(1);
        orderRequest.setAddDate(new Date());
        orderRequest.setOrderType(1);
        orderRequest.setSourceClient(6);
        orderRequest.setCatalog(1);
        orderRequest.setShop(request.getShop());
        orderRequest.setStoreId(request.getStore());
        orderRequest.setOpenId(request.getOpenId());
        OrderUtils.configDate(orderRequest);
        OrderResponse order = orderApi.createData(orderRequest);


        OrderAddressRequest orderAddressRequest=new OrderAddressRequest();
        orderAddressRequest.setOrder(order.getId());
        orderAddressRequest.setAddress(address.getAddress());
        orderAddressRequest.setArea(address.getArea());
        orderAddressRequest.setCity(address.getCity());
        orderAddressRequest.setConsignee(address.getName());
        orderAddressRequest.setHouseNo(address.getHouseNo());
        orderAddressRequest.setLat(address.getLat());
        orderAddressRequest.setLng(address.getLng());
        orderAddressRequest.setProvince(address.getProvince());
        orderAddressRequest.setTel(address.getTel());
        orderAddressRequest.setPhone(address.getPhone());
        orderAddressRequest.setPostalCode(address.getPostalCode());
        orderAddressApi.createData(orderAddressRequest);

        for (ShoppingCartSimple shoppingCartSimple : skuList) {
            ShoppingCartRequest req=new ShoppingCartRequest();
            req.setId(shoppingCartSimple.getId());
            shoppingCartApi.delete(req);
        }

        for (ShoppingCartSimple shoppingCartSimple : skuList) {
            OrderItemRequest itemRequest=new OrderItemRequest();
            BeanUtils.copyProperties(shoppingCartSimple,itemRequest);
            itemRequest.setNum(new BigDecimal(shoppingCartSimple.getNum()));
            itemRequest.setPrice(shoppingCartSimple.getPrice());
            itemRequest.setTotal(shoppingCartSimple.getPrice().multiply(itemRequest.getNum()));
            itemRequest.setOrder(order.getId());
            itemRequest.setSkuId(shoppingCartSimple.getSku());
            itemRequest.setProductId(shoppingCartSimple.getProduct());
            itemRequest.setProductImageUrl(shoppingCartSimple.getProductLogo());
            if (shoppingCartSimple.getSku()!=null){
                itemRequest.setSkuType(2);
            }else{
                itemRequest.setSkuType(1);
            }
            orderItemApi.createData(itemRequest);
        }
        result.getData().put("order",order);

        //检查库存
        OrderPayRequest req=new OrderPayRequest();
        req.setDataId(order.getId());
        req.setPayHandler("orderPayHandler");
        req.setMoney(order.getAmount());
        req.setShop(order.getShop());
        req.setUser(order.getCustomerId());
        req.setOpenId(request.getOpenId());
        return  paymentExtApi.pay(req);
    }
}
